<?php

namespace app\company\controller;

use app\common\enum\order\PickStatus;
use app\common\enum\order\ReceiveType;
use app\common\model\Goods as GoodsModel;
use app\common\controller\CompanyController;
use app\common\enum\order\CheckStatus;
use app\common\enum\order\GoodsType;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\OrderType;
use app\common\exception\BaseException;
use app\common\model\CompanyWarehouse;
use app\common\model\Dealer;
use app\common\model\GoodsSpec;
use app\common\model\SalesmanStore;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyImportOrder;
use app\company\model\CompanyOrder;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyPickOrder;
use app\company\model\CompanyPickOrderDetail;
use app\common\model\DealerGoods;
use app\common\model\DealerGoodsSpec;
use app\common\model\Refund;
use app\common\model\Salesman;
use app\common\model\Store;
use app\company\model\StoreBalanceLog;
use app\Request;
use \think\App;
use think\facade\Db;
use think\response\Json;
use jianyan\excel\Excel;
use  app\company\controller\Order as OrderController;

/**
 * @ControllerAnnotation(title="销售管理")
 */
class SaleOrder extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model           = new CompanyOrder();
        $this->importHeader    = [
                '*订单号', '*下单时间', '*经销商', '*业务员', '*门店名称',
                '是否自提(1否,2是)', '*商品名称', '*商品条码', '*单位类型(1小单位,2大单位,3中单位)', '*结算方式(1现结,2账期,3预存款)',
                '*数量', '*销售单价', '*下单价', '整单备注', '明细备注'
        ];
        $this->defaultTemplate = [
                'order_no', 'create_time', 'dealer_name', 'salesman_name', 'store_name',
                'is_self_order', 'goods_name', 'code69', 'unit_type', 'receive_type',
                'num', 'sale_price', 'true_price', 'order_remark', 'detail_remark'
        ];
        $this->fileName        = '销售单导入模版';
    }

    /**
     * @NodeAnnotation(title="订单列表")
     */
    public function list(): Json
    {
        list($limit, $where) = $this->buildSearchParams();
        $goodsName = $this->request->get('goods_name', '');

        if ($goodsName) {
            $dealerGoodsSubQuery = Db::name('dealer_goods')
                                     ->where('company_id', $this->companyId)
                                     ->where('name', 'like', '%' . $goodsName . '%')
                                     ->field('id')
                                     ->buildSql();

            $companyOrderDetailSubQuery = Db::name('company_order_detail')
                                            ->whereIn('dealer_goods_id', $dealerGoodsSubQuery)
                                            ->field('company_order_id')
                                            ->buildSql();

            $where[] = ['id', 'in', $companyOrderDetailSubQuery];
        }

        // 查询构造
        $query = $this->model->with([
                                            'detail'   => function ($query)
                                            {
                                                $query->with([
                                                                     'goods'     => function ($query)
                                                                     {
                                                                         $query->field('id,image,name,code69')
                                                                               ->withTrashed();
                                                                     },
                                                                     'goodsSpec' => function ($query)
                                                                     {
                                                                         $query->field('id,image,name,unit,sale_price,unit_type')
                                                                               ->withTrashed();
                                                                     },
                                                                     'warehouse',
                                                             ]);
                                            },
                                            'store'    => function ($query)
                                            {
                                                $query->field('id,name,contact,address,phone');
                                            },
                                            'dealer'   => function ($query)
                                            {
                                                $query->field('id,name');
                                            },
                                            'salesman' => function ($query)
                                            {
                                                $query->field('id,rename');
                                            }
                                    ])
                             ->where('order_type', OrderType::SALES)
                             ->where($where)
                             ->where($this->defaultWhere)
                             ->where('check_status', 2)
                             ->where('order_status', '<>', OrderStatus::CANCEL);

        // 计算汇总数据
        $totalQuery = clone $query; // 避免分页查询影响汇总数据

        // 分页查询
        $paginator = $query->order($this->sort)
                           ->paginate($limit);

        // 处理分页数据
        $paginator->each(function ($item)
        {
            $outMoney = 0;
            $detail   = $item->detail->each(function ($detailItem)
            {
                return [
                        'num'        => $detailItem->num,
                        'sale_price' => $detailItem->goodsSpec->sale_price ?? 0,
                        'unit_type'  => $detailItem->goodsSpec->unit_type ?? 0,
                ];
            });

            foreach ($detail as $v) {
                $outMoney += $v['num'] * $v['sale_price'];
            }

            $item->out_money        = round($outMoney, 2);
            $item->appointment_time = $item->appointment_time ? date('Y-m-d H:i:s', $item->appointment_time) : '暂无';
        });

        // 计算汇总数据
        $amount        = $totalQuery->sum('order_amount');
        $pay_amount    = $totalQuery->sum('pay_amount');
        $no_pay_amount = $totalQuery->sum('unsay_amount');
        $items = $paginator->items();
        $goods_amount = array_sum(array_column($items, 'out_money'));
        return $this->success([
                                      'list'          => $paginator,
                                      'amount'        => $amount,
                                      'goods_amount'  => $goods_amount,
                                      'pay_amount'    => $pay_amount,
                                      'no_pay_amount' => $no_pay_amount,
                              ]);
    }

    /**
     * @NodeAnnotation(title="订单拣货")
     * @throws BaseException
     */
    public function pick(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $id   = $request->post('id', '');
        if (empty($id)) return $this->error('订单ID不能为空');
        $id = explode(',', $id);
        if (empty($post['type']) || $post['type'] != 1) return $this->error('当前请求参数非法！');
        try {
            $this->model->transaction(function () use ($id)
            {
                // 判断是否已经存在捡货单
                array_walk($id, function ($v)
                {
                    //查询捡货详情
                    $pickOrderDetail = CompanyPickOrderDetail::where('company_order_id', $v)->find();
                    if ($pickOrderDetail) {
                        $orderNo = $this->model->where('id', $v)->value('order_no');
                        throw new BaseException(['message' => '订单【' . $orderNo . '】已存在拣货单中']);
                    }
                });
                // 过滤订单
                $orderIds = $this->model->where('id', 'in', $id)
                        //                                        ->where('order_status', OrderStatus::PASS)
                                        ->where('order_status', OrderStatus::BEING)
                                        ->where('check_status', 2)
                                        ->column('id');
                if (empty($orderIds)) throw new BaseException(['message' => '该配送单包含的订单已存在拣货单中,无法重复拣货']);
                // 生成分拣单
                $outOrder = new CompanyPickOrder();
                $outOrder->save([
                                        'company_id'        => $this->companyId,
                                        'pick_order_no'     => generateOrderNo('PK'),
                                        'company_order_ids' => implode(',', $orderIds),
                                        'order_num'         => count($orderIds),
                                        'pick_num'          => CompanyOrderDetail::whereIn(
                                                'company_order_id',
                                                $orderIds
                                        )->sum('num'),
                                        'true_pick_num'     => CompanyOrderDetail::whereIn(
                                                'company_order_id',
                                                $orderIds
                                        )->sum('num')
                                ]);
                // 生成分拣单详情表
                if ($outOrder) {
                    $detail = array_map(function ($id) use ($outOrder)
                    {
                        $dealerId = $this->model->where('id', $id)->value('dealer_id');
                        return [
                                'company_pick_order_id' => $outOrder->id,
                                'company_order_id'      => $id,
                                'dealer_id'             => $dealerId,
                        ];
                    }, $orderIds);
                    $outOrder->detail()->saveAll($detail);
                }
                // 修改拣货状态
                $this->model->whereIn('id', $orderIds)->save(['pick_status' => PickStatus::PICKED]);
                //                $this->model->save(['order_status' => OrderStatus::FINISH]);
            });
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('拣货成功');
    }

    /**
     * @NodeAnnotation(title="导入")
     * @throws BaseException
     */
    public function import(Request $request): Json
    {

        $this->checkPost();
        $type = $request->post('type',
                               1);
        $file = $request->file('file');
        if (!$file) return $this->error('请上传文件！');
        // 保存文件到临时目录
        $savePath = $file->move('storage' . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR);
        // 获取文件的完整路径
        $savePath = $savePath->getPathname();
        $this->model->startTrans();
        try {
            $data = Excel::import($savePath, 1, false, 'Xlsx', './storage/temp/excelImg/');
            if (!$data) throw new BaseException(['message' => '文件内容为空！']);
            if ($type == 1) {
                if (!$this->importHeader) throw new BaseException(['message' => '请联系管理设置文件模版！']);
                if (array_filter($data[0]) != $this->importHeader) throw new BaseException(['message' => '文件模版错误！']);
            }

            if ($type == 2) {
                //舟谱订单导入
                //                $importHeader = [
                //                        '综合订单号', '单据', '审核时间', '出(入)库时间', '业务员',
                //                        '送货员', '客户名称', '仓库', '业务属性', '付款方式',
                //                        '标签', '商品名称', '下单数量', '单位名称', '大单位价格',
                //                        '下单金额', '体积', '重量', '出入库数量', '单位名称',
                //                        '出入库金额', '签收数量', '单位名称', '签收金额', '订单状态',
                //                        '结款状态', '预估毛利', '销售结算数量', '单位名称', '销售结算金额',
                //                        '退货结算数量', '单位名称', '退货结算金额', '销售结算价', '销售退货结算价',
                //                        '结算单位', '成本金额', '毛利', '成本毛利率', '销售毛利率',
                //                        '整单备注', '明细备注', '超级标记'
                //                ];
                //                $importHeader = [
                //                        '单据','业务员','客户名称','仓库','业务属性',
                //                        '标签','商品名称','下单数量','单位名称','大单位价格',
                //                        '下单金额','订单状态','销售结算数量','单位名称','销售结算金额',
                //                        '退货结算数量','单位名称','退货结算金额','整单备注','明细备注','订单时间'
                //                ];
                $importHeader = [
                        '单据', '审核时间', '期望生产日期', '出(入)库时间', '签收时间',
                        '业务员', '送货员', '协送员', '客户名称', '客户片区',
                        '仓库', '业务属性', '标签', '商品名称', '下单数量',
                        '单位名称', '大单位价格', '下单金额', '出入库数量', '单位名称',
                        '出入库金额', '订单状态', '销售结算数量', '单位名称', '销售结算金额',
                        '退货结算数量', '单位名称', '退货结算金额', '整单备注', '明细备注'
                ];
                if (!$importHeader) throw new BaseException(['message' => '模版错误请联系管理！']);
                $data = array_slice($data, 4);
            }

            // 去掉表头
            unset($data[0]);
            $data = array_filter($data);
            array_pop($data);
            if ($type == 1) {
                $this->dealOrder($data);
            }
            if ($type == 2) {
                $this->zpDealOrder($data);
            }
            $this->model->commit();
        } catch (\Exception $e) {
            $this->model->rollback();
            @unlink($savePath);
            return $this->error('导入失败' . $e->getMessage() . $e->getLine());
        }
        @unlink($savePath);
        return $this->success('导入成功');
    }

    private function dealOrder(mixed $data): void
    {
        if (empty($data)) throw new BaseException(['message' => '文件内容为空！']);
        $orders = array_map(function ($vo)
        {
            $fields = $this->defaultTemplate;
            $data   = array_combine($fields, $vo);
            // 验证表格中的值
            $rule = [
                    'order_no|订单号'       => 'require',
                    'create_time|下单时间'  => 'require',
                    'dealer_name|经销商'    => 'require',
                    'salesman_name|业务员'  => 'require',
                    'store_name|门店名称'   => 'require',
                    'goods_name|商品名称'   => 'require',
                    'code69|商品条码'       => 'require',
                    'unit_type|单位类型'    => 'require',
                    'receive_type|结算方式' => 'require',
                    'num|数量'              => 'require',
                    'sale_price|销售单价'   => 'require',
                    'true_price|下单价'     => 'require',
            ];
            $this->validate($data, $rule);
            return $data;
        }, $data);

        // 订单号去重
        $orderNos = array_unique(array_column($orders, 'order_no'));
        // 逻辑处理
        foreach ($orderNos as $orderNo) {
            $orderInfo = (new CompanyOrder())->where('order_no', $orderNo)->where('company_id', $this->companyId)
                                             ->find();
            if ($orderInfo) {
                // 跳出本次循环
                continue;
            }
            // 匹配订单
            $filteredArray = array_filter($orders, function ($item) use ($orderNo)
            {
                return $item['order_no'] === $orderNo;
            });
            // 重组
            $orderData = array_values($filteredArray);
            // 订单公共信息
            $commonOrder = [
                    'company_id'  => $this->companyId,
                    'order_no'    => $orderNo,
                    'create_time' => strtotime($orderData[0]['create_time']),

                    'remark'        => $orderData[0]['order_remark'] ?? '',
                    'is_self_order' => $orderData[0]['is_self_order'] ?? 1,
                    'check_status'  => CheckStatus::YES_CHECK,
                    'order_channel' => 1,
            ];

            $commonOrder['receive_type'] = $orderData[0]['receive_type'] ?? 1;

            $commonOrder['dealer_id'] = Dealer::where('company_id', $this->companyId)
                                              ->where('name', $orderData[0]['dealer_name'])
                                              ->value('id');
            if (!$commonOrder['dealer_id']) throw new BaseException(["message" => "经销商【{$orderData[0]['dealer_name']}】不存在！"]);


            $commonOrder['salesman_id'] = Salesman::where('company_id', $this->companyId)
                                                  ->where('rename', $orderData[0]['salesman_name'])
                                                  ->value('id');
            if (!$commonOrder['salesman_id']) throw new BaseException(["message" => "业务员【{$orderData[0]['salesman_name']}】不存在！"]);

            $commonOrder['store_id'] = Store::where('company_id', $this->companyId)
                                            ->where('name', $orderData[0]['store_name'])
                                            ->value('id');
            if (!$commonOrder['store_id']) throw new BaseException(["message" => "门店【{$orderData[0]['store_name']}】不存在！"]);

            // 主订单
            $order = $commonOrder;
            // 订单金额
            $order_amount = 0;
            foreach ($orderData as $value) {
                $order_amount += $value['sale_price'] * $value['num'];
            }
            $order['order_amount'] = sprintf("%.2f", $order_amount);
            // 子订单
            $info       = $commonOrder;
            $childOrder = [];
            // 根据类型组装子订单
            $info['order_no']      = $order['order_no'] . '-' . OrderType::SALES;
            $info['order_type']    = OrderType::SALES;
            $info['order_amount']  = array_sum(array_column($orderData, 'order_amount'));
            $info['return_amount'] = 0;
            $info['unsay_amount']  = $info['order_amount'];
            $unitNum               = 0;

            $details = array_map(function ($vo) use ($info, &$unitNum)
            {
                $detail = [
                        'goods_type'  => 1,
                        'true_price'  => $vo['true_price'],
                        'sale_price'  => $vo['sale_price'],
                        'num'         => $vo['num'],
                        'total_price' => $vo['sale_price'] * $vo['num'],
                        'remark'      => $vo['detail_remark']
                ];

                $goodsInfo = DealerGoods::where('dealer_id', $info['dealer_id'])
                                        ->where('name', $vo['goods_name'])
                                        ->find()
                                        ->toArray();

                $detail['dealer_goods_id'] = $goodsInfo['id'] ?? '';

                $dealer_info = Dealer::where('id', $goodsInfo['dealer_id'])->find()->toArray();

                $vo['dealer_name'] = $dealer_info['name'];
                if (!$detail['dealer_goods_id']) throw new BaseException(["message" => "经销商【{$vo['dealer_name']}】商品【{$vo['goods_name']}】不存在！"]);
                $detail['dealer_goods_spec_id'] = DealerGoodsSpec::where('dealer_goods_id',
                                                                         $detail['dealer_goods_id'])
                                                                 ->where('unit_type', $vo['unit_type'])
                                                                 ->value('id') ?? '';


                if (!$detail['dealer_goods_spec_id']) throw new BaseException(["message" => "经销商【{$vo['dealer_name']}】商品【{$vo['goods_name']}】规格单位【{$vo['unit_type']}】不存在！"]);
                // TODO 仓库后期需要选择录入
                //                $detail['company_warehouse_id'] = CompanyWarehouse::where('company_id', $this->companyId)
                //                                                                  ->value('id');

                $specInfo = DealerGoodsSpec::where('id', $detail['dealer_goods_spec_id'])->find();

                $unitNum += $specInfo->ratio * $vo['num'];

                $detail['driver_money']        = $specInfo->driver_money * $vo['num'];
                $detail['assist_driver_money'] = $specInfo->assist_driver_money * $vo['num'];

                $specInfo->inc('actual_sales', $vo['num'])
                         ->inc('virtual_sales', $vo['num'])
                         ->save();

                return $detail;
            }, $orderData);

            $info['driver_money']        = array_sum(array_column($details, 'driver_money'));
            $info['assist_driver_money'] = array_sum(array_column($details, 'assist_driver_money'));

            $totalUnitNum = $unitNum;
            // 获取当前$details 中的 dealer_goods_id;
            $dealerGoodsId = array_unique(array_column($details, 'dealer_goods_id'));
            // 判断库存
            $goodsInfo = (new DealerGoods())->where('id', implode(',', $dealerGoodsId))->find();
            if ($totalUnitNum > $goodsInfo->sales_stock) throw new BaseException(["message" => "商品【{$goodsInfo->name}】剩余库存不足本次导入！"]);
            // 扣减库存
            $goodsInfo->inc('virtual_sales', $totalUnitNum)
                      ->inc('actual_sales', $totalUnitNum)
                      ->dec('sales_stock', $totalUnitNum)
                      ->save();
            $info['detail'] = $details;
            $childOrder[]   = $info;

            // 新增主订单
            $orderModel = new CompanyOrder();
            $save       = $orderModel->save($order);
            if (!$save) throw new BaseException(["message" => "订单保存失败！"]);
            // 新增子订单
            $childOrder = array_map(function ($vo) use ($orderModel)
            {
                $vo['pid'] = $orderModel->id;
                return $vo;
            }, $childOrder);

            $childOrderInfo = $orderModel->saveAll($childOrder);

            // 保存订单详情
            $childOrderInfo = $childOrderInfo->toArray();

            array_walk($childOrderInfo, function ($v)
            {
                $detail = $v['detail'];
                foreach ($detail as &$item) {
                    $item['company_order_id']  = $v['id'];
                    $item['company_order_pid'] = $v['pid'];
                }
                // 新增订单详情
                (new CompanyOrderDetail())->insertAll($detail);
            });

            // 如果对应订单内是预存款结算，需要把预存款转入冻结金额字段
            $userInfo         = ['receive_type' => $commonOrder['receive_type'], 'salesman_id' => $commonOrder['salesman_id'], 'store_id' => $commonOrder['store_id']];
            $orderMoney       = array_sum(array_column($orderData, 'order_amount'));
            $order_controller = new OrderController(new App());
            $order_controller->dealYc1($userInfo, $orderMoney);
        }
    }

    /**
     * 舟谱数据处理
     */
    private function zpDealOrder(array $data): void
    {
        if (empty($data)) throw new BaseException(['message' => '文件内容为空！']);
        $orders = array_map(function ($vo)
        {

            //            $fields = [
            //                    'a', 'order_no', 'create_time', 'd', 'e','salesman_name',
            //                    'f', 'store_name', 'h', 'i', 'receive_type_msg',
            //                    'k', 'goods_name', 'num', 'unit', 'big_unit_price','l',
            //                    'order_amount', 'volume', 'weight', 's', 't',
            //                    'u', 'v', 'w', 'x', 'y',
            //                    'z', 'aa', 'ab', 'ac', 'ad',
            //                    'ae', 'af', 'ag', 'ah', 'ai',
            //                    'aj', 'ak', 'al', 'am', 'an',
            //                    'remark', 'detail_remark', 'aq'
            //            ];
            //            $fields = [
            //                    'order_no','salesman_name','store_name','d','e',
            //                    'f','goods_name','num','unit','big_unit_price','order_amount',
            //                    'l','m','n','o','p','q','r','remark','detail_remark','create_time'
            //            ];
            $fields = [
                    'order_no', 'create_time', 'c', 'd', 'e',
                    'salesman_name', 'g', 'h', 'store_name', 'j',
                    'k', 'l', 'm', 'goods_name', 'num', 'unit', 'big_unit_price', 'order_amount',
                    's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'aa', 'ab', 'remark', 'detail_remark'
            ];
            if (count($fields) != count($vo)) throw new BaseException(['message' => '文件内容格式错误！']);
            // 将数组中的值与字段名组合成一个新的关联数组
            $order                 = array_combine($fields, $vo);
            $data['order_no']      = $order['order_no'];
            $data['create_time']   = $order['create_time'];
            $data['salesman_name'] = $order['salesman_name'];
            $data['store_name']    = $order['store_name'];
            $data['goods_name']    = $order['goods_name'];
            //            $data['receive_type_msg'] = $order['receive_type_msg'];
            $data['num']           = $order['num'];
            $data['unit']          = $order['unit'];
            $data['order_amount']  = $order['order_amount'];
            $data['remark']        = $order['remark'];
            $data['detail_remark'] = $order['detail_remark'];
            $rule                  = [
                    'order_no|订单号'      => 'require',
                    'create_time|下单时间' => 'require',
                    'salesman_name|业务员' => 'require',
                    'store_name|门店名称'  => 'require',
                    'goods_name|商品名称'  => 'require',
                    //                    'receive_type_msg|结算方式' => 'require',
                    'num|数量'             => 'require',
            ];
            $this->validate($data, $rule);
            return $data;
        }, $data);
        // 订单号去重
        $orderNos  = array_values(array_unique(array_column($orders, 'order_no')));
        $orderList = [];
        foreach ($orderNos as $orderNo) {
            $orderInfo = (new CompanyOrder())->where('order_no', $orderNo)->where('order_type', 1)
                                             ->where('company_id', $this->companyId)
                                             ->find();
            if ($orderInfo) {
                // 跳出本次循环
                continue;
            }

            // 匹配订单
            $filteredArray = array_filter($orders, function ($item) use ($orderNo)
            {
                return $item['order_no'] === $orderNo;
            });
            // 重组
            $orderData = array_values($filteredArray);

            $order = [
                    'company_id'    => $this->companyId,
                    'order_no'      => $orderNo,
                    'create_time'   => strtotime($orderData[0]['create_time']),
                    'remark'        => $orderData[0]['order_remark'] ?? '',
                    'check_status'  => CheckStatus::YES_CHECK,
                    'order_channel' => 3,
                    'order_type'    => 1,
                    'receive_type'  => 1,
            ];

            //            switch ($orderData[0]['receive_type_msg']) {
            //                case '现结':
            //                    $order['receive_type'] = 1;
            //                    break;
            //                case '账期':
            //                    $order['receive_type'] = 2;
            //                    break;
            //                case '预存款' || '预付款':
            //                    $order['receive_type'] = 3;
            //
            //            }
            $order['salesman_id'] = (new Salesman())->where('company_id', $this->companyId)
                                                    ->where('rename', $orderData[0]['salesman_name'])
                                                    ->value('id');
            if (!$order['salesman_id']) throw new BaseException(["message" => "业务员【{$orderData[0]['salesman_name']}】不存在！"]);

            $order['dealer_id'] = (new DealerGoods())->where('company_id', $this->companyId)
                                                     ->where('name', $orderData[0]['goods_name'])
                                                     ->value('dealer_id');
            if (!$order['dealer_id']) throw new BaseException(["message" => "商品【{$orderData[0]['goods_name']}】不存在！"]);

            $order['store_id'] = (new Store())->where('company_id', $this->companyId)
                                              ->where('name', $orderData[0]['store_name'])
                                              ->value('id');
            if (!$order['store_id']) throw new BaseException(["message" => "门店【{$orderData[0]['store_name']}】不存在！"]);


            // 订单金额
            $order['order_amount'] = sprintf("%.2f", array_sum(array_column($orderData, 'order_amount')));
            // 新增主订单
            $orderModel = new CompanyOrder();
            $orderId    = $orderModel->insertGetId($order);
            if (!$orderId) throw new BaseException(["message" => "订单" . $orderNo . "创建失败！"]);

            $details = [];
            foreach ($orderData as $v) {
                $detail    = [
                        'goods_type' => $v['order_amount'] > 0 ? 1 : 2,
                        'dealer_id'  => $order['dealer_id'],
                        'company_id' => $this->companyId,
                ];
                $goodsInfo = (new DealerGoods())->where('company_id', $this->companyId)
                                                ->where('dealer_id', $detail['dealer_id'])
                                                ->where('name', $v['goods_name'])->find();
                if (!$goodsInfo) throw new BaseException(["message" => "商品【{$v['goods_name']}】不存在！"]);

                $detail['dealer_goods_id'] = $goodsInfo->id;
                if (!$detail['dealer_goods_id']) throw new BaseException(["message" => "商品【{$v['goods_name']}】不存在！"]);
                $specInfo = (new DealerGoodsSpec())->where('dealer_goods_id', $detail['dealer_goods_id'])
                                                   ->where('unit_type', 2)
                                                   ->find();
                $ratio    = 1;
                if ($specInfo) {
                    $ratio = $specInfo->ratio;
                    if (!$ratio) throw new BaseException(["message" => "商品【{$v['goods_name']}】未设置规格比，请联系管理员！"]);
                } else {
                    $specInfo = (new DealerGoodsSpec())->where('dealer_goods_id', $detail['dealer_goods_id'])
                                                       ->where('unit_type', 1)
                                                       ->find();
                    if (!$specInfo) throw new BaseException(["message" => "商品【{$v['goods_name']}】不存在小单位规格！"]);
                }
                // 数量除以比例
                $detail['num'] = bcdiv($v['num'], $ratio);
                // 获取余数
                $num = $v['num'] % $ratio;
                if ($num > 0) {
                    $specInfo = (new DealerGoodsSpec())->where('dealer_goods_id', $detail['dealer_goods_id'])
                                                       ->where('unit', $v['unit'])->find();
                    if (!$specInfo) throw new BaseException(["message" => "商品【{$v['goods_name']}】不存在当前规格【{$v['unit']}】！"]);
                    $detail['num'] = $v['num'];
                }
                $detail['dealer_goods_spec_id'] = $specInfo->id;
                $detail['sale_price']           = $specInfo->sale_price;
                $detail['true_price']           = bcdiv($v['order_amount'], $detail['num'], 2);
                $detail['total_price']          = $v['order_amount'];
                $detail['remark']               = $v['detail_remark'];
                $detail['company_order_id']     = $orderId;
                $detail['company_order_pid']    = $orderId;
                if ($v['num'] > $goodsInfo->sales_stock) throw new BaseException(["message" => "商品【{$goodsInfo->name}】剩余库存不足本次导入！"]);
                // 扣减库存
                $goodsInfo->inc('virtual_sales', $v['num'])
                          ->inc('actual_sales', $v['num'])
                          ->dec('sales_stock', $v['num'])
                          ->save();

                $details[] = $detail;
            }
            $order['detail'] = $details;
            // TODO 可以在循环后打印排查问题
            $orderList[] = $order;

            //             保存订单详情
            (new CompanyOrderDetail())->insertAll($details);

            // 如果对应订单内是预存款结算，需要把预存款转入冻结金额字段
            $userInfo = ['receive_type' => $order['receive_type'], 'salesman_id' => $order['salesman_id'], 'store_id' => $order['store_id']];
            $this->dealYc1($userInfo, $order['order_amount']);
        }
        //        halt($orderList);
    }

    private function dealYc1($post, $orderMoney): void
    {
        if ($post['receive_type'] == ReceiveType::YC) {
            $salesmanStoreInfo = (new SalesmanStore())->where('store_id', $post['store_id'])
                                                      ->where('salesman_id', $post['salesman_id'])->find();
            $oldBalance        = $salesmanStoreInfo['balance'];
            $oldFreeze         = $salesmanStoreInfo['freeze'];
            if ($salesmanStoreInfo['balance'] < $orderMoney) $orderMoney = $salesmanStoreInfo['balance'];
            $salesmanStoreInfo->dec('balance', $orderMoney)->inc('freeze', $orderMoney)->save();
            $companyOrderId = $this->model->where('pid', $this->model->id)->where('order_type', OrderType::SALES)
                                          ->value('id');
            $this->model->where('id', $companyOrderId)->save(['yc_money' => $orderMoney]);
            // 生成余额变动记录
            $data = [
                    'company_id'       => $this->companyId,
                    'salesman_id'      => $post['salesman_id'],
                    'store_id'         => $post['store_id'],
                    'creator_type'     => StoreBalanceLog::TYPE_SALESMAN,
                    'creator_id'       => $post['salesman_id'],
                    'company_order_id' => $companyOrderId,
                    'old_balance'      => $oldBalance,
                    'new_balance'      => bcsub($oldBalance, $orderMoney, 2),
                    'old_freeze'       => $oldFreeze,
                    'new_freeze'       => bcadd($oldFreeze, $orderMoney, 2),
                    'remark'           => StoreBalanceLog::REMARK_ORDER,
            ];
            (new StoreBalanceLog())->save($data);
        }
    }
}
